package com.heaton.videocar.view;


/**
 * 项目名： SeekBarColorPicker-master
 * 包名： com.csdn.seekbarcolorpicker_master
 * 文件名字： SeekBarColorPicker
 * 创建时间：2017/10/31 20:27
 * 项目名： Xuhong  http://blog.csdn.net/xh870189248
 * 描述： 七彩色圆环采集器
 */

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.Image;
import android.media.ImageReader;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;

import com.heaton.baselib.utils.LogUtils;

import java.nio.ByteBuffer;

public class CircleView extends View {
    //圆环的画笔
    private Paint paintCircleRing;

    //最里面的圆的画笔，默认是绿色
    private Paint paintInnerColor;
    //圆形选择器
    private Paint paintSelecter;

    //宽度
    private int width;
    //高度
    private int height;

    //圆环的宽
    private int barWidth = 8;

    //内圆的半径
    private float innerRadius;
    //外圆的半径
    private float outerRadius;

    //圆的坐标
    private float circleX, circleY;

    private float markPointX, markPointY;

    //默认角度
    private int angle = 0;

    //当前进度值
    private int progress = 50;

    //开启机智云的rgb灯模式,默认不开启
    private boolean isGizwitLight = false;

    public CircleView(Context context) {
        super(context);
        init();
    }

    public CircleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 渐变色环参数
        paintCircleRing = new Paint(Paint.ANTI_ALIAS_FLAG);
        paintCircleRing.setAntiAlias(true);
        paintCircleRing.setStyle(Paint.Style.STROKE);
        paintCircleRing.setStrokeWidth(30);

        //内圆参数
        paintInnerColor = new Paint();
        paintInnerColor.setColor(Color.WHITE);
        paintInnerColor.setAntiAlias(true);
        paintInnerColor.setStrokeWidth(5);

        //选择器
        paintSelecter = new Paint();
        paintSelecter.setColor(Color.WHITE);
//        paintSelecter.setStyle(Paint.Style.STROKE);
        paintSelecter.setStyle(Paint.Style.FILL);
        paintSelecter.setAntiAlias(true);
        paintSelecter.setStrokeWidth(8);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        barWidth = dp2px(getContext(), 2);
        width = getMeasuredWidth();
        height = getMeasuredHeight()-dp2px(getContext(), 60);
        //选择最小
        int size = (width > height) ? height : width;

        //确定圆的x坐标中心点
        circleX = width / 2;
        //确定圆的Y坐标中心点
        circleY = height / 2 + dp2px(getContext(), 30);

        Log.e(TAG, "size:" + size + " circleX:" + circleX + " circleY:" + circleY + " width:" + width + " height:" + height);
        //分辨率适配:获取圆环的宽度 圆环的半径 内部圆的半径
        paintCircleRing.setStrokeWidth(30);
//        outerRadius = size / 2 - dp2px(getContext(), 2);
        outerRadius = size / 2 - barWidth;
        innerRadius = outerRadius - barWidth;
        //circleX 渲染中心点x坐标，circleY渲染中心y点坐标；mCircleColors为渐变颜色内容
        paintCircleRing.setColor(getResources().getColor(android.R.color.transparent));

    }

    @Override
    protected void onDraw(Canvas canvas) {
        //画色环
        canvas.drawCircle(circleX, circleY, outerRadius, paintCircleRing);
        //画最里面的圆，默认是绿色
//        canvas.drawCircle(circleX, circleY, innerRadius / 2, paintInnerColor);

        setInitMarkToXY(getAngle());

        float frameRadius = outerRadius - innerRadius + dp2px(getContext(), 4);
        canvas.drawCircle(markPointX, markPointY, frameRadius+15, paintSelecter);
        super.onDraw(canvas);
    }

    private void setInitMarkToXY(int angle) {
        markPointX = (float) (circleX + outerRadius
                * Math.sin(angle * Math.PI / 180));
        markPointY = (float) (circleY - outerRadius
                * Math.cos(angle * Math.PI / 180));
        invalidate();
    }

    String TAG = "SeekBarColor";

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float markRange = dp2px(getContext(), 60);
        float x = event.getX();
        float y = event.getY();
        boolean up = false;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.e(TAG, "onTouchEvent: " + "按下");
                if (x < markPointX + markRange && x > markPointX - markRange
                        && y > markPointY - markRange && y < markPointY + markRange) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    Log.e(TAG, "onTouchEvent: " + "按下1");
                }
                moved(x, y, up);
                break;
            case MotionEvent.ACTION_MOVE:
                moved(x, y, up);
                break;
            case MotionEvent.ACTION_UP:
                up = true;
                moved(x, y, up);
                if (!isMarkPointRange(x, y)) {
                    if (mSeekBarColorPickerChangeListener != null) {
                        mSeekBarColorPickerChangeListener.onClick();
                    }
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                getParent().requestDisallowInterceptTouchEvent(false);
                up = true;
                moved(x, y, up);
                break;
        }
        return true;
    }


    private boolean isMarkPointRange(float x, float y) {
        float range = dp2px(getContext(), 60);
        return x > (markPointX - range) && x < (markPointX + range) && y > (markPointY - range) && y < (markPointY + range);
    }

    private void moved(float x, float y, boolean up) {
        //判断触摸点是否在圆环内
//        Log.e(TAG, "判断触摸点是否在圆环内:" + isMarkPointRange(x, y));
        float distance = (float) Math.sqrt(Math.pow((x - circleX), 2)
                + Math.pow((y - circleY), 2));
        if (distance < outerRadius + 400 && distance > innerRadius - 400 && !up) {
            markPointX = (float) (circleX + outerRadius * Math.cos(Math.atan2(x - circleX, circleY - y) - (Math.PI / 2)));
            markPointY = (float) (circleY + outerRadius * Math.sin(Math.atan2(x - circleX, circleY - y) - (Math.PI / 2)));
            float degrees = (float) ((float) ((Math.toDegrees(Math.atan2(x - circleX, circleY - y)) + 360.0)) % 360.0);
            // 注意：为负数要加360°
            if (degrees < 0) {
                degrees += 2 * Math.PI;
            }
            //禁止掉过渡层滑动
            if (degrees > 150 && degrees < 210){
                return;
            }
            //TODO 210-360=>0-50    0-150=>50-100
            int progressValue = 0;
            if (degrees>=210 && degrees<=360){//0-50
                progressValue = (int) (Math.floor(degrees-210)/3);
            }else {//50-100
//                progressValue = Math.round(degrees/3)+50;
                progressValue = (int) (Math.ceil(degrees/3)+50);
            }
            progress = 100 - progressValue;
            //改变内部圆的颜色
            Log.e(TAG, "改变内部圆的颜色：角度:" + degrees + " x:" + x + " y:" + y);
            //角度四舍五入
            this.angle = Math.round(degrees);
            if (mSeekBarColorPickerChangeListener != null) {
                LogUtils.logi("SeekBarColor>>>[moved]: "+progress);
                mSeekBarColorPickerChangeListener.onProgressChange(this, progress, (int) markPointX, (int) markPointY);
            }
            invalidate();
        } else {
            invalidate();
        }
    }

    public int getProgress() {
        return progress;
    }

    public void setProgress(int progress1) {
        this.progress = progress1;
        int progress = 100-progress1;
        int angle = 0;
        if (progress<50){//0-50
            angle = progress*3+210;
        }else {//50-100
            angle = (progress-50)*3;
        }
        this.angle = angle;
        setInitMarkToXY(angle);
    }

    //获取圆环上颜色
    private int interpCircleColor(int colors[], float degree) {
        degree -= 90;

        if (degree < 0)
            degree += 360;

        float p = degree * (colors.length - 1) / 360;
        int i = (int) p;
        p -= i;

        int c0 = colors[i];
        int c1 = colors[i + 1];
        int a = ave(Color.alpha(c0), Color.alpha(c1), p);
        int r = ave(Color.red(c0), Color.red(c1), p);
        int g = ave(Color.green(c0), Color.green(c1), p);
        int b = ave(Color.blue(c0), Color.blue(c1), p);
        return Color.argb(a, r, g, b);
    }

    /* private float fromColor2Degree(int color) {

         float degree = 0;
         int diff = 360 / (mCircleColors.length - 1);

         int r = Color.red(color);
         int g = Color.green(color);
         int b = Color.blue(color);

         int[] mColor = {b, g, r};

         // 把最大的，置0xFF，最小的，置0
         int min = findMin(b, g, r);
         int max = findMax(b, g, r);

         int temp = (0xff << (max * 8)) + (0xff << (8 * 3));

         if (max == min) {//证明RGB相等；
             return 90;// 九十度
         }

         int mid = 3 - max - min;
         int start = 0;
         int end = 0;
         for (int i = 0; i < mCircleColors.length - 2; i++) {
             if (mCircleColors[i] - temp == 0)
                 start = i;
             if (mCircleColors[i] - temp == (0xff << (mid * 8)))
                 end = i;
         }
         float percent = (float) mColor[mid] / (float) 0xff;
         int degreeDiff = (int) (percent * diff);

         if (start < end) {
             degree = start * diff;
             degree += degreeDiff;
         } else {
             degree = start * diff;
             degree -= degreeDiff;
         }

         degree += 90;

         if (degree > 360)
             degree -= 360;
         return degree;
     }
 */
    private int colorFilter(int color) {
        int result = 0;

        int r = Color.red(color);
        int g = Color.green(color);
        int b = Color.blue(color);

        int[] mColor = {b, g, r};

        // 把最大的，置0xFF，最小的，置0
        int min = findMin(b, g, r);
        int max = findMax(b, g, r);

        if (mColor[min] != 0 || mColor[max] != 0xff)
            return result;

        result = Color.argb(255, mColor[2], mColor[1], mColor[0]);

        return result;
    }

    private int findMin(int one, int two, int three) {
        if (one < two && one < three) {
            return 0;
        } else if (two < three) {
            return 1;
        } else {
            return 2;
        }
    }

    private int findMax(int one, int two, int three) {
        if (one > two && one > three) {
            return 0;
        } else if (two > three) {
            return 1;
        } else {
            return 2;
        }
    }

    private int ave(int s, int d, float p) {
        return s + Math.round(p * (d - s));
    }

    private static int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());
    }

    private int getAngle() {
        return angle;
    }


    public interface SeekBarColorPickerChangeListener {
        void onProgressChange(CircleView circleView, int progress, int x, int y);

        void onClick();
    }

    public void setSeekBarColorPickerChangeListener(SeekBarColorPickerChangeListener mSeekBarColorPickerChangeListener) {
        this.mSeekBarColorPickerChangeListener = mSeekBarColorPickerChangeListener;
    }

    private SeekBarColorPickerChangeListener mSeekBarColorPickerChangeListener;

    /**
     * 通过int设置color
     *
     * @param color 整型
     */
    /*public void setColorByInt(int color) {


        if (isGizwitLight) {

            int data_LED_R = Color.red(color);
            int data_LED_G = Color.green(color);
            int data_LED_B = Color.blue(color);

            if (data_LED_R == 254) {
                data_LED_R = 255;
            }
            if (data_LED_G == 254) {
                data_LED_G = 255;
            }
            if (data_LED_B == 254) {
                data_LED_B = 255;
            }
            color = Color.argb(255, data_LED_R, data_LED_G, data_LED_B);
        }

        int colorFilter = colorFilter(color);
        // 颜色格式不符合，不做响应
        if (colorFilter == 0) {
            return;
        }
        // set内圈的颜色
        paintInnerColor.setColor(colorFilter);
        // set外圈的角度
        float degree = fromColor2Degree(colorFilter);
        this.angle = Math.round(degree);

    }*/
    public void setPaintInnerColor(int color) {
        if (paintInnerColor != null) {
            paintInnerColor.setColor(color);
            invalidate();
        }

    }


    public boolean isGizwitLight() {
        return isGizwitLight;
    }

    public void setGizwitLight(boolean gizwitLight) {
        isGizwitLight = gizwitLight;
    }

    public static class GBData {
        private static final String TAG = "GBData";
        ImageReader reader;
        private Bitmap bitmap;

        public int getColor(int x, int y) {
            if (reader == null) {
                Log.w(TAG, "getColor: reader is null");
                return -1;
            }

            Image image = reader.acquireLatestImage();

            if (image == null) {
                if (bitmap == null) {
                    Log.w(TAG, "getColor: image is null");
                    return -1;
                }
                return bitmap.getPixel(x, y);
            }
            int width = image.getWidth();
            int height = image.getHeight();
            final Image.Plane[] planes = image.getPlanes();
            final ByteBuffer buffer = planes[0].getBuffer();
            int pixelStride = planes[0].getPixelStride();
            int rowStride = planes[0].getRowStride();
            int rowPadding = rowStride - pixelStride * width;
            if (bitmap == null) {
                bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
            }
            bitmap.copyPixelsFromBuffer(buffer);
            image.close();

            return bitmap.getPixel(x, y);
        }
    }
}


